﻿using System;
using System.IO;
using System.Xml;
using System.Xml.XPath;
using System.Xml.Xsl;

namespace Songhay.Xml
{

    /// <summary>
    /// Static helper members for XML-related routines.
    /// </summary>
    /// <remarks>
    /// These definitions are biased toward
    /// emitting <see cref="System.Xml.XPath.XPathDocument"/> sets.
    /// However, many accept any input implementing the
    /// <see cref="System.Xml.XPath.IXPathNavigable"/> interface.
    /// </remarks>
    public static partial class XmlUtility
    {


        /// <summary>
        /// Transfers the data in the Source to the Destination.
        /// </summary>
        /// <param name="readerSource"><see cref="System.Xml.XmlTextReader"/></param>
        /// <param name="writerDestination"><see cref="System.Xml.XmlTextWriter"/></param>
        public static void WriteReader(ref XmlTextReader readerSource, ref XmlTextWriter writerDestination)
        {
            if (writerDestination == null) throw new ArgumentException("Argument writerDestination is null.");

            while ((readerSource != null) && !readerSource.EOF)
            { writerDestination.WriteNode(readerSource, false); }
        }


        /// <summary>
        /// Transforms the specified navigable documents
        /// and writes to disk with the specified path.
        /// </summary>
        /// <param name="xmlInput">The specified input.</param>
        /// <param name="navigableSet">
        /// The source <see cref="System.Xml.XPath.IXPathNavigable"/> set.
        /// </param>
        /// <param name="outputPath">
        /// The file-system, target path.
        /// </param>
        public static void WriteXslTransform(IXPathNavigable xmlInput, IXPathNavigable navigableSet, string outputPath)
        {
            using (FileStream fs = new FileStream(outputPath, FileMode.Create))
            {
                XslCompiledTransform xslt = new XslCompiledTransform(false);
                xslt.Load(navigableSet);
                xslt.Transform(xmlInput, null, fs);
            }
        }


        /// <summary>
        /// Transforms the specfied input and writes to disk.
        /// </summary>
        /// <param name="xmlInput">The specified input.</param>
        /// <param name="navigableSet">
        /// The source <see cref="System.Xml.XPath.IXPathNavigable"/> set.
        /// </param>
        /// <param name="outputPath">
        /// The file-system, target path.
        /// </param>
        public static void WriteXslTransform(XmlReader xmlInput, IXPathNavigable navigableSet, string outputPath)
        {
            using (FileStream fs = new FileStream(outputPath, FileMode.Create))
            {
                XslCompiledTransform xslt = new XslCompiledTransform(false);
                xslt.Load(navigableSet);
                xslt.Transform(xmlInput, null, fs);
            }
        }
    }
}
